package com.niiwoo.civet.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.mobile.vo.request.UploadFileRequestVO;
import com.niiwoo.civet.mobile.vo.request.user.ImGetUserBasicInfoRequestVO;
import com.niiwoo.civet.mobile.vo.response.TokenValidResponseVO;
import com.niiwoo.civet.mobile.vo.response.user.ImGetUserBasicInfoResponseVO;
import com.niiwoo.civet.mobile.vo.response.user.ImUploadImageResponseVO;
import com.niiwoo.civet.user.dto.request.QueryUserBasicInfoRequestDTO;
import com.niiwoo.civet.user.dto.response.ImGetUserBasicInfoResponseDTO;
import com.niiwoo.civet.user.enums.QueryBasicInfoEnum;
import com.niiwoo.civet.user.enums.UserEnum;
import com.niiwoo.civet.user.service.ImDubboService;
import com.niiwoo.tripod.base.utils.MD5Util;
import com.niiwoo.tripod.consumer.component.FileUploadHandler;
import com.niiwoo.tripod.consumer.properties.FileUploadProperties;
import com.niiwoo.tripod.consumer.util.FileMediaExtensions;
import com.niiwoo.tripod.consumer.util.ImageUploadUtil;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by huangmin on 2017/12/19.
 */
@Slf4j
@RestController
@RequestMapping("/im")
@Api(tags = "IM数据对接", description = "/im")
public class IMController {

    @Reference(version = "1.0.0")
    private ImDubboService imDubboService;

    @Autowired
    private FileUploadHandler fileUploadHandler;

    //意见反馈输入长度限制
    private static final String PASSWORD = "C4F91A5BBC60ECC0";//互相约定的密码

    @ApiOperation(value = "token校验")
    @PostMapping("/token/valid")
    public Result<TokenValidResponseVO> tokenValid() {
        TokenValidResponseVO responseVO = new TokenValidResponseVO();
        responseVO.setUserId(String.valueOf(PrincipalContext.getUserId()));
        return Result.with(responseVO);
    }

    @AuthIgnore
    @ApiOperation(value = "手机号码、用户Id查询用户信息(黄敏)")
    @PostMapping("/imGetUserBasicInfo")
    public Result<ImGetUserBasicInfoResponseVO> imGetUserBasicInfo(@RequestBody @Valid ImGetUserBasicInfoRequestVO requestVO) {
        if(requestVO.getType() == null || requestVO.getType() == 0 || StringUtils.isBlank(requestVO.getKey())){
            throw new BizException("USR10023");
        }
        if (StringUtils.isBlank(requestVO.getMobileNo()) && StringUtils.isBlank(requestVO.getUserId())){
            throw new BizException("USR10030");
        }
        if(!this.checkKey(requestVO.getUserId(), requestVO.getMobileNo(), requestVO.getType(), requestVO.getKey())){
            throw new BizException("USR10043");
        }

        ImGetUserBasicInfoResponseVO responseVO = new ImGetUserBasicInfoResponseVO();
        QueryUserBasicInfoRequestDTO requestDTO = new QueryUserBasicInfoRequestDTO();
        requestDTO.setType(QueryBasicInfoEnum.enumOf(requestVO.getType()));
        if(requestVO.getType().equals(QueryBasicInfoEnum.USER_ID.getValue())){
            requestDTO.setUserId(requestVO.getUserId());
        }else if(requestVO.getType().equals(QueryBasicInfoEnum.MOBILE_NO.getValue())) {
            requestDTO.setMobileNo(requestVO.getMobileNo());
        }
        ImGetUserBasicInfoResponseDTO responseDTO = imDubboService.imGetUserBasicInfo(requestDTO);
        responseVO.setBusinessId(responseDTO.getUserId());
        responseVO.setMobile(responseDTO.getMobile());
        responseVO.setNickName(responseDTO.getNickName());
        responseVO.setAvatar(responseDTO.getHeadImage());
        responseVO.setGender(responseDTO.getGender());
        responseVO.setIntroduction(responseDTO.getPersonalSign());
        responseVO.setArea(responseDTO.getHeadImage());
        responseVO.setIdentity(responseDTO.getIdentity());
        responseVO.setCompany(responseDTO.getCompany());
        responseVO.setOccupation(responseDTO.getOccupation());
        responseVO.setArea(responseDTO.getArea());
        responseVO.setIndustry(responseDTO.getIndustry());

        String[] identityTag =  responseDTO.getIdentityTag().split(",");
        for(String identity : identityTag){
            if(UserEnum.IdentityTag.BORROWER.getType().equals(identity))
                responseVO.setBorrower(Byte.valueOf("1"));
            if(UserEnum.IdentityTag.INVESTOR.getType().equals(identity))
                responseVO.setIsInvestor( Byte.valueOf("1"));
        }
        return Result.with(responseVO);
    }

    @AuthIgnore
    @ApiOperation(value = "IM上传文件(黄敏)")
    @PostMapping("/imUploadFile")
    public Result<ImUploadImageResponseVO> imUploadFile(@RequestBody @Valid UploadFileRequestVO requestVO) {
        log.info("IM上传文件###requestVO={}",JSON.toJSON(requestVO));
        ImUploadImageResponseVO responseVO = new ImUploadImageResponseVO();
        FileUploadProperties.FileUploadResult fileUploadResult;
        byte[] fileByte = Base64.decodeBase64(requestVO.getFile());
        //获取文件后缀
        String extName = FileMediaExtensions.parseMediaExtension(requestVO.getFile());
        log.info("IM上传文件###extName={}:",extName);
        if(ImageUploadUtil.checkType(extName)){
            fileUploadResult = fileUploadHandler.upload(fileByte, true, extName);
        }else{
            fileUploadResult = fileUploadHandler.saveAttachment(fileByte, extName);
        }
        responseVO.setFileUrl(fileUploadResult.getImageUrl());
        responseVO.setSmallImageUrl(fileUploadResult.getSmallImageUrl());
        return Result.with(responseVO);
    }

    private boolean checkKey(String userId, String mobileNo, Byte type, String key) {
        String signStr;
        if (Byte.valueOf("1").equals(type)) {
            signStr = "userId=" + userId + "&type=" + type + "&password=" + PASSWORD;
        } else {
            signStr = "mobileNo=" + mobileNo + "&type=" + type + "&password=" + PASSWORD;
        }
        String sign = MD5Util.md5(signStr);
        return sign.equals(key);
    }

}
